import hashlib
from django.shortcuts import HttpResponse
from system.settings.utils import AppSetting


class SignAuthentication:
    def __init__(self, func):
        self.func = func

    def __call__(self, request, *args, **kwargs):
        sign = request.GET.get("sign", "")
        if sign == "":
            return HttpResponse("接口签名为空！")
        # 签名检查
        md5 = hashlib.md5()
        sign_str = AppSetting.get('api_key')
        sign_bytes_utf8 = str(sign_str).encode(encoding="utf-8")
        md5.update(sign_bytes_utf8)
        server_sign = md5.hexdigest()
        if server_sign != sign:
            return HttpResponse("接口签名失败！请重新请求")
        else:
            return self.func(request)
